package com.promise.jokerdream.work.penguin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryChaosWarResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.database.entity.ChaosWarGameConfigEntity

// 乱斗刷新任务工作
class ChaosWarRefreshWork(
    override val uin: String,
    private val config: ChaosWarGameConfigEntity
): BaseWork(uin) {

    override val name: String
        get() = "乱斗"

    override val priority: Int
        get() = 3

    private val gameApi = GameApi.Companion.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.Companion.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        try {
            // 1. 查询乱斗信息
            val queryResult = gameApi.queryChaosWar()
            return queryResult.foldWithApiException(
                onSuccess = { response ->
                    processChaosWarRefresh(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            return WorkResult.Failure(e, e.message)
        }
    }

    private suspend fun processChaosWarRefresh(response: QueryChaosWarResponse): WorkResult {
        var currentResponse = response
        var refreshCount = 0
        val maxRefreshAttempts = 10 // 防止无限循环

        // 使用传入配置的选中任务
            val selectedTasks = if (config.selectedTasks.isEmpty()) emptyList() else config.selectedTasks.split(",").map { it.trim() }
        if (selectedTasks.isEmpty()) {
            return WorkResult.Success // 如果没有配置任务，直接返回
        }

        while (refreshCount < maxRefreshAttempts) {
            // 2. 检查每日完成次数
            if (currentResponse.dailyCompNum >= currentResponse.dailyCanCompNum) {
                return WorkResult.Success
            }

            // 3. 检查刷新次数
            if (currentResponse.dailyFreeRefreshTimes == 0) {
                return WorkResult.Success
            }

            // 4. 检查有效任务
            val validTasks = currentResponse.taskArray.filter { task ->
                // 检查任务描述是否在配置的任务列表中
                val isConfigTask = selectedTasks.any { configTask ->
                    task.desc == configTask
                }
                // state为2表示未完成，state为3表示已完成，都是有效任务
                isConfigTask && (task.state == 2 || task.state == 3)
            }

            if (validTasks.isNotEmpty()) {
                return WorkResult.Success
            }

            // 5. 执行刷新
            val refreshResult = gameApi.refreshChaosWar()
            val refreshSuccess = refreshResult.foldWithApiException(
                onSuccess = { refreshResponse ->
                    true
                },
                onFailure = { code, msg ->
                    false
                }
            )

            if (!refreshSuccess) {
                return WorkResult.Failure(Exception("刷新失败"), "刷新失败")
            }

            refreshCount++

            // 6. 重新查询乱斗信息
            val reQueryResult = gameApi.queryChaosWar()
            val reQuerySuccess = reQueryResult.foldWithApiException(
                onSuccess = { newResponse ->
                    currentResponse = newResponse
                    true
                },
                onFailure = { code, msg ->
                    false
                }
            )

            if (!reQuerySuccess) {
                return WorkResult.Failure(Exception("重新查询失败"), "重新查询失败")
            }
        }

        return WorkResult.Success
    }
}